package com.hui.jwt.security;

/**
 * @BelongsProject: SpringSecurity-jwt
 * @BelongsPackage: com.hui.jwt.security
 * @Author: HUI
 * @CreateTime: 2022-04-02 20:59
 * @Description:
 */

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * 自定义认证失败
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        System.err.println("认证失败");
        HashMap<String, Object> map = new HashMap<>();
        map.put("message", "认证失败："+authException.getMessage());
        response.setStatus(HttpStatus.UNAUTHORIZED.value());

        response.setContentType("text/json;charset=utf-8");
        String value = new ObjectMapper().writeValueAsString(map);

        response.getWriter().println(value);
    }
}
